package com.sh.learning.demo.javakafkaproducer.serivce;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sh.learning.demo.common.message.RegistrationMessage;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author songHai
 * @Classname MessageService
 * @Description
 * @Date 2025/4/30 0:57
 */
@Component
public class MessageService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public void sendRegistrationMessage(RegistrationMessage msg) throws IOException {
        send("topic_registration", msg);
    }

    private void send(String topic, Object msg) throws IOException {
        ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, objectMapper.writeValueAsString(msg));
        producerRecord.headers().add("type", msg.getClass().getName().getBytes(StandardCharsets.UTF_8));
        kafkaTemplate.send(producerRecord);
    }
}
